//
//  JBComposeViewController.swift
//  sinaBlog
//
//  Created by jobo on 15/11/6.
//  Copyright © 2015年 jobo. All rights reserved.
//

import UIKit
import SVProgressHUD

class JBComposeViewController: UIViewController {

    //toolBar 的底部约束
    var toolBarBottomConstraint : NSLayoutConstraint?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

    
        self.view.backgroundColor = UIColor.whiteColor()
        
        prepareForUI()
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        composeTextView.becomeFirstResponder()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //设置ui
    func prepareForUI()
    {
        setNavigationItem()
        
        setNavTitle()
        
        setToolbar()
        
        setUpComposeTextView()
    }
    
    // MARK : 设置导航title
    func setNavTitle()
    {
        
        let name = JBUserAccount.loadAccount()?.name
        let titleBase = "发微博"
        if name != nil
        {
            
            let navigationTitle = titleBase + "\n" + name!
            let lable = UILabel()
            lable.numberOfLines = 0
            lable.textAlignment = NSTextAlignment.Center
            //lable.text = navigationTitle
            //添加属性文本
            let attributeString =  NSMutableAttributedString(string: navigationTitle)
            //设置name属性
            let nameRange = (navigationTitle as NSString).rangeOfString(name!)
            attributeString.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(11), NSForegroundColorAttributeName: UIColor.lightGrayColor()], range: nameRange)
            //设置title属性
            let titleRange = (navigationTitle as NSString).rangeOfString(titleBase)
            attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: titleRange)
            //设置label属性文本
            lable.attributedText = attributeString
            lable.sizeToFit()
            navigationItem.titleView = lable
        }
        else
        {
            self.navigationItem.title = titleBase
        }
    }
    
    // MARK : 设置导航栏按钮
    func setNavigationItem()
    {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelLeftBtn")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sentRightBtn")
        self.navigationItem.rightBarButtonItem?.enabled = false
        
    }
    
    
    //设置toolbar
    func setToolbar()
    {
        //添加toolbar
        view.addSubview(toolBar)
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        //添加约束
//        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        toolBarBottomConstraint = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)

        view.addConstraint(toolBarBottomConstraint!)
        
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.mainScreen().bounds.width))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 44))

        //toolBar.frame = CGRectMake(0, 200, 375, 44)
        
        var items = [UIBarButtonItem]()
        
        
        
        let itemSettings =
        [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]
        ]
        
        
        for dict in itemSettings
        {
            // 获取图片名称
            let name = dict["imageName"]!
            let nameHighlight = name + "_highlighted"
            let item = UIButton()
            item.setImage(UIImage(named: name), forState: UIControlState.Normal)
            item.setImage(UIImage(named: nameHighlight), forState: UIControlState.Highlighted)
            item.sizeToFit()
            //按钮点击事件
            let action = dict["action"]!
            
            item.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)

            print(nameHighlight)
            
            items.append(UIBarButtonItem(customView: item))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    
    //设置textView
    func setUpComposeTextView()
    {
        view.addSubview(composeTextView)
        
        composeTextView.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: composeTextView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: composeTextView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 64))
        
        view.addConstraint(NSLayoutConstraint(item: composeTextView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: composeTextView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        
       //composeTextView.backgroundColor = UIColor.lightGrayColor()
    }

    //取消按钮点击事件
    func cancelLeftBtn()
    {
        print("取消")
        composeTextView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }

    
    
    //发送微博按钮点击事件
    func sentRightBtn()
    {
        print("发送")
        SVProgressHUD.showSuccessWithStatus("正在发送", maskType: SVProgressHUDMaskType.Black)
        
        
        
        
    }
    
    
    //toolBar 键盘切换点击事件五个
    func picture()
    {
        print("pic")
    }
    func trend()
    {
        print("trend")
    }
    func mention()
    {
        print("mention")
        
    }
    func emoticon()
    {
        print("emoticon")
        
        
        
        composeTextView.resignFirstResponder()
        
        
        //延迟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            
            self.composeTextView.inputView = self.composeTextView.inputView == nil ? self.emoticonViewController.view : nil
            
            self.composeTextView.becomeFirstResponder()

        }
        
       
    }
    func add()
    {
        print("add")
    }
    
    
    //toolBar 通知实现
    func keyboardWillChangeFrame(notification : NSNotification)
    {
        print(notification)
        //键盘最后的frame值
        let keyboardEndFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        print(keyboardEndFrame)
        //改变tool 的约束
        toolBarBottomConstraint?.constant = (keyboardEndFrame?.origin.y)! - UIScreen.mainScreen().bounds.height
        
        //获取键盘弹出的时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        //设置动画效果
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    //注销通知
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    
    // 懒加载
    lazy var toolBar : UIToolbar =
    {
        let toolBar =  UIToolbar()
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        return toolBar
    }()
    
    
    //懒加载textview
    lazy var composeTextView : UITextView =
    {
        let cpTV = JBPlaceholderTextView()
        
        //设置字体大小
        cpTV.font  =  UIFont.systemFontOfSize(18)

        //设置垂直方向回弹效果
        cpTV.alwaysBounceVertical = true
        
        //设置textview滑动时候键盘消失
        cpTV.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        cpTV.placeholder = "分享新鲜事儿..."
        
        
        //设置代理
        cpTV.delegate = self
        
        return cpTV
    }()
    
    lazy var emoticonViewController : CZEmoticonViewController =
    {
        
        
        let emoticonViewController = CZEmoticonViewController()
        
        self.addChildViewController(emoticonViewController)
        
        emoticonViewController.textView = self.composeTextView
        
        return emoticonViewController
    }()
    
}
extension JBComposeViewController: UITextViewDelegate {
    
    // 文字改变代理方法
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

